import errno
import os
import re

def sanitize_filename(filename):
    return re.sub('[^-a-zA-Z0-9_.,()!#+ ]+', '_', filename)

def mkdir_p(path):
    try:
        os.makedirs(path)
    except OSError, exc:
        if exc.errno == errno.EEXIST:
            pass
        else:
            raise

def get_unique_filename(filename, filenames):
    if not filename in filenames:
        return filename
    base, ext = os.path.splitext(filename)
    i = 2
    while filename in filenames:
        filename = base + ' (%02i)' % i + ext
        i += 1
    return filename
